var express = require("express");
var router = express.Router();
var { user, home, area } = require("../model/model");
const multiparty = require("multiparty");


// 租房信息渲染
router.get("/rental", async (req, res) => {
  const { page, pagesize, name } = req.query;
  console.log(name);
  let query = {};
  if (name) {
    // 使用正则表达式进行模糊搜索
    query.name = new RegExp(name, 'i'); // 'i' 表示不区分大小写
  }
  try {
    let data = await home
      .find(query)
      .skip((page - 1) * pagesize)
      .limit(pagesize);
    // console.log(data);
    res.send({
      data,
      code: 200,
    });
  } catch (error) {
    console.error(error);
    res.status(500).send({
      code: 500,
      msg: "服务器错误",
    });
  }
});

// 详情页渲染
router.get("/detail", async (req, res) => {
  let data = await home.find();
  res.send({
    data,
    code: 200,
  });
});

// 用户渲染
router.get("/user", async (req, res) => {
  let data = await user.find();
  res.send({
    data,
    code: 200,
  });
});

// 修改新密码
router.post("/changepwd", async (req, res) => {
  console.log(req.body);
  try {
    await user.updateOne(
      { _id: req.body.id },
      { $set: { password: req.body.newpwd } }
    );
    res.send({
      code: 200,
      msg: "修改成功"
    });
  } catch (error) {
    console.log(error);
    res.status(500).send({
      code: 500,
      msg: "服务器错误",
    });
  }
});

//根据id获取用户信息
router.get("/getuser", async (req, res) => {
  let data = await user.find({ _id: req.query.id });
  res.send({
    data,
    code: 200,
  });
})

//根据id更新个人信息
router.post("/updateuser", async (req, res) => {
  console.log(req.body);

  await user.updateOne(
    { _id: req.query.id },
    {
      $set: {
        admin: req.body.admin,
        sex: req.body.sex,
        age: req.body.age,
        address: req.body.address,
        work: req.body.work,
        landlord: req.body.landlord,
      }
    }
  );
  res.send({
    code: 200,
    msg: "修改成功"
  })
})


//图片上传
router.post('/upload', async (req, res) => {
  const Form = new multiparty.Form();
  Form.uploadDir = "upload";
  Form.parse(req, async (err, fields, files) => {
    if (err) {
      console.log(err);
      res.status(500).send({
        code: 500,
        msg: "服务器错误",
      });
    } else {
      res.send({
        code: 200,
        msg: "上传成功",
        data: 'http://localhost:3000/' + files.file[0].path
      });
    }
  })
})


module.exports = router;